﻿using CatUtils.Utils.Currency;
using CatUtils.Utils.Currency.IoUtils;
using CatUtils.Utils.Currency.TextUtils;
using CatUtils.Utils.SpecialUtils.PicBed.Smms;
using CatUtils.Utils.SpecialUtils.View;
using CatUtils.Utils.TypeConvert;
using CatUtilsDll.Utils.Currency.WebUtils;
using Newtonsoft.Json;
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Net.Security;

using System.Security.Cryptography.X509Certificates;
using CatUtils.Utils.SpecialUtils.Html;

namespace CatUtils.Utils.SpecialUtils.PicBed.Sina
{
    public static class SinaImgUploadTool
    {
        /// <summary>
        /// 强制解除证书验证。
        /// </summary>
        public static void InitSecurity()
        {
            ServicePointManager.ServerCertificateValidationCallback += RemoteCertificateValidate;
        }

        public static bool RemoteCertificateValidate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors error)
        {
            PrintLog.Log("警告！为了通过证书验证，总是返回true");

            return true;
        }

        /// <summary>
        /// 文件上传异常状态码
        /// </summary>
        public static class ErrorCode
        {
            /// <summary>
            /// 文件为空时触发
            /// </summary>
            public static readonly string FileEmpty = "FileEmpty";
        }

        /// <summary>
        /// 保证程序只打开一个新登录窗口
        /// </summary>
        public static bool LoginFormFlag = false;

        /// <summary>
        /// 上传到API
        /// </summary>
        public static string UploadAPI =
     "https://picupload.weibo.com/interface/pic_upload.php?s=xml&ori=1&data=1&rotate=0&wm=&app=miniblog&mime=image";

        /// <summary>
        /// 获取图片大小
        /// </summary>
        public static class SinaImgSize
        {//square,thumb150,orj360,orj480,mw690,mw1024,mw2048,small,bmiddle,large
            /// <summary>
            /// 正方形
            /// </summary>
            public static string Square { get; } = "square";

            /// <summary>
            /// 预览图 150
            /// </summary>
            public static string thumb150 { get; } = "thumb150";

            /// <summary>
            /// 预览图 360
            /// </summary>
            public static string orj360 { get; } = "orj360";

            /// <summary>
            /// 预览图 480
            /// </summary>
            public static string orj480 { get; } = "orj480";

            /// <summary>
            /// 预览图 690 推荐
            /// </summary>
            public static string mw690 { get; } = "mw690";

            /// <summary>
            /// 预览图 1024 推荐
            /// </summary>
            public static string mw1024 { get; } = "mw1024";

            /// <summary>
            /// 预览图 2048
            /// </summary>
            public static string mw2048 { get; } = "mw2048";

            /// <summary>
            /// 预览图 小
            /// </summary>
            public static string small { get; } = "small";

            /// <summary>
            ///预览图 中等
            /// </summary>
            public static string bmiddle { get; } = "bmiddle";

            /// <summary>
            /// 预览图 大尺寸 推荐
            /// </summary>
            public static string large { get; } = "large";
        }

        /// <summary>
        /// 修改SinaImg链接的大小格式
        /// </summary>
        /// <param name="SinaImgLink"></param>
        /// <param name="SinaImgSize">请调用SinaImgSize的参数</param>
        /// <returns></returns>
        public static string SinaImgLinkResize(string SinaImgLink, string SinaImgSize)
        {
            return TextHelper.ReplaceTextEnhance(SinaImgLink, "sinaimg.cn/.*?/", $"sinaimg.cn/{SinaImgSize}/");
        }

        /// <summary>

        /// 上传图片链接
        /// </summary>
        /// <param name="ImgUrl"></param>
        /// <returns></returns>
        public static string UploadImgLink(string ImgUrl)
        {
            return UploadByte(WebHelper.ByteDownload(ImgUrl, WebHelper.PcWebHeader()));
        }

        /// <summary>
        /// 上传文件byte
        /// </summary>
        /// <param name="FileByte"></param>
        /// <returns></returns>
        public static string UploadByte(byte[] FileByte)
        {
            if (FileByte == null)
                return "";
            string FilePath = FileNameHelper.CreateTempFileName() + ".jpg";
            new ByteConvert().ByteToFile(FileByte, FilePath);

            string ImgUrl = UploadFile(FilePath);
            FileHelper.FileDelete(FilePath);
            return ImgUrl;
        }

        /// <summary>
        /// 上传一个文件
        /// </summary>
        /// <param name="FileName"></param>
        /// <returns></returns>
        public static string UploadFile(string FileName)
        {
            WebHeaderCollection headers = new WebHeaderCollection();
            string BoundaryText = "----WebKitFormBoundary" + TextHelper.GetRandomString(16);
            headers.Add("Host", "picupload.weibo.com");
            headers.Add("Origin", "chrome-extension://fdfdnfpdplfbbnemmmoklbfjbhecpnhf");
            headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.79 Safari/537.36");
            headers.Add("Accept", "*/*");
            headers.Add("Referer", "https://weibo.com/u/5495506653/home?wvr=5&sudaref=graph.qq.com");

            headers.Add("Accept-Language", "zh-CN,zh;q=0.9");
            headers.Add("Cookie", FileHelper.ReadAllText(SinaStaticvalue.CookiesFile));
            headers.Add("Content-Type", "multipart/form-data");
            Console.WriteLine(FileHelper.ReadAllText(SinaStaticvalue.CookiesFile));
            string ImgInfo = UpLoadImg(headers, BoundaryText, FileName);
            Console.WriteLine($"SinaLink:{ImgInfo}");
            if (ImgInfo != "")
            {
                return ImgInfo;
            }
            else
                return "";
        }

        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="headers"></param>
        /// <param name="boundaryText"></param>
        /// <param name="FileName"></param>
        /// <returns></returns>
        private static string UpLoadImg(WebHeaderCollection headers, string boundaryText, string FileName)
        {
            try
            {
                //InitSecurity();
                using (WebClient webClient = new WebClient())
                {
                    webClient.Headers = headers;
                    byte[] responseData = webClient.UploadData(UploadAPI + WebHelper.UrlEncode(FileNameHelper.GetFileType(FileName).Replace(".", "/")),
                      "POST", new ByteConvert().FileToBytes(FileName)); // 得到返回字符流
                    string Shtml = Encoding.UTF8.GetString(responseData);// 解码
                    Console.WriteLine(Shtml);
                    return AnalysisXml(Shtml);
                }
            }
            catch (Exception ex) { PrintLog.Log(ex); }
            return "";
        }

        /// <summary>
        /// 分析返回结果
        /// </summary>
        /// <param name="ReadJson"></param>
        /// <returns></returns>
        private static string AnalysisXml(string ReadJson)
        {
            try
            {
                string GetPid = HtmlHelper.GetFirstText(ReadJson, "//pid");
                if (GetPid == "")
                    return "";
                return string.Format("http://tva1.sinaimg.cn/large/{0}.jpg", GetPid);
            }
            catch (Exception ex)
            {
                PrintLog.Log(ex);
            }

            return "";
        }

        private class PicJson
        {
            public class Pic_1
            {
                /// <summary>
                ///
                /// </summary>
                public int width { get; set; }

                /// <summary>
                ///
                /// </summary>
                public int size { get; set; }

                /// <summary>
                ///
                /// </summary>
                public int ret { get; set; }

                /// <summary>
                ///
                /// </summary>
                public int height { get; set; }

                /// <summary>
                ///
                /// </summary>
                public string name { get; set; }

                /// <summary>
                ///
                /// </summary>
                public string pid { get; set; }
            }

            public class Pics
            {
                /// <summary>
                ///
                /// </summary>
                public Pic_1 pic_1 { get; set; }
            }

            public class Data
            {
                /// <summary>
                ///
                /// </summary>
                public int count { get; set; }

                /// <summary>
                ///
                /// </summary>
                public string data { get; set; }

                /// <summary>
                ///
                /// </summary>
                public Pics pics { get; set; }
            }

            public class Root
            {
                /// <summary>
                ///
                /// </summary>
                public string code { get; set; }

                /// <summary>
                ///
                /// </summary>
                public Data data { get; set; }
            }
        }

        /// <summary>
        /// 文件转码到base64
        /// </summary>
        /// <param name="Imagefilename"></param>
        /// <returns></returns>
        private static string FileToBase64string(string Imagefilename)
        {
            try
            {
                using (FileStream filestream = new FileStream(Imagefilename, FileMode.Open))
                {
                    byte[] bt = new byte[filestream.Length];

                    //调用read读取方法
                    filestream.Read(bt, 0, bt.Length);
                    string base64Str = Convert.ToBase64String(bt);

                    return base64Str;
                }
            }
            catch (Exception ex)
            {
                PrintLog.Log("ImgToBase64string 转换失败\nException:" + ex.Message);
            }
            return "";
        }
    }
}